<?php
/**
 * Notes:
 * User: wudg <544038230@qq.com>
 * Date: 2025/3/31 11:59
 */

namespace App\Controller\Socket;


use App\Service\Socket\WebSocketService;
use Hyperf\Di\Annotation\Inject;
use Hyperf\SocketIOServer\Annotation\SocketIONamespace;
use Hyperf\SocketIOServer\BaseNamespace;
use Hyperf\SocketIOServer\Socket;
use Hyperf\SocketIOServer\Annotation\Event;
use Hyperf\Codec\Json;


#[SocketIONamespace("/")]
class WebSocketController extends BaseNamespace
{

    #[Inject]
    protected WebSocketService $webSocketService;


    #[Event("connect")]
    public function connect(Socket $socket)
    {
        $userId= auth('sso')->id();

        $this->webSocketService->bindSidUid($socket->getSid(),$userId);
        $socket->join($userId); //用uid 作为房间号，后续其他服务推送通知已uid 推送
    }


    /**
     * 断开链接
     * @param Socket $socket
     * @return void
     */
    #[Event("disconnect")]
    public function disconnect(Socket $socket)
    {

        $sid = $socket->getSid();
        $this->webSocketService->clearSid($sid);
        $this->emit('disconnect',  '用户'.$socket->getSid().'断开' );

    }


    #[Event("event")]
    public function onEvent(Socket $socket, $data)
    {
//        $userId= auth('sso')->id();
//        var_dump("用户uid:{$userId}发消息：".$data);
//        return $socket->emit('event',$data);
        // 应答
        return 'Event Received: ' . $data;

    }


    /**
     * @param string $data
     */
    #[Event("join-room")]
    public function onJoinRoom(Socket $socket, $data)
    {
        if(!is_array($data) || empty($data['roomId']) || empty($data['userId']) || empty($data['userName']))
        {
            return $socket->emit('event',$this->response('error', [],'参数错误',400));
        }

        if($data['roomId'] == -1)
        {
            $socket->join($data['userId']);
            return$socket->to($data['userId'])->emit('event', $this->response('success',[],'加入成功'));
        }else{
            $socket->join($data['roomId']);
            $socket->to($data['userId'])->emit('event', $this->response('success',[],'加入成功'));

            // 向房间内所有人广播（含当前用户）
            return $this->emit('event', 'There are ' . count($socket->getAdapter()->clients($data['roomId'])) . " players in {$data['userId']}");
        }
    }

    /**
     * 发送uid
     * @param Socket $socket
     * @param $data
     * @return void
     */
    #[Event("say-uid")]
    public function sayUid(Socket $socket, $data)
    {
        $uid = (int)$this->webSocketService->sidGetUid($socket->getSid());
        if(empty($data['uid']) || empty($data['message'])) {
            $socket->emit('event',$this->response('error', [],'发送消息失败,参数缺失',400));
            return;
        }

        $socket->to($data['uid'])->emit('message', $this->response('priMsg', [
            'message_id' => $data['uid'],
            'send_id' => $uid,
            'send_avatar' => $data['avatar'] ?? "",
            'receiver_id' => $data['uid'],
            'content' => $data['message'],
            'send_time' =>time(),
            'attachments' => [],
        ]));
    }




    /**
     * @param string $data
     */
    #[Event("say")]
    public function onSay(Socket $socket, $data)
    {
        $data = Json::decode($data);
        $uid = $this->webSocketService->sidGetUid($socket->getSid());
        $socket->to($data['room'])->emit('event', $socket->getSid() . " uid:{$uid} say: {$data['message']}");
    }
    
    protected function response(string $type,array $data = [],string $msg= '',int $code = 200)
    {
        return json_encode([
            'type' => $type,
            'data' => $data,
            'msg' => $msg,
            'code' => $code
        ],JSON_UNESCAPED_UNICODE);
    }
}